<script setup>
import { computed, ref, onMounted, getCurrentInstance } from 'vue';
import { useLanguageStore } from '@/stores/language';
import { useRegisterStore } from '@/stores/register';
import {useAuthStore} from "@/stores/auth.js";
import { ElMessage } from 'element-plus';
import router from '@/router';
import {fetchCaptcha, submitLogin, submitRegister} from '@/api/sign';
import {useTokenStore} from "@/stores/token.js";
const { proxy } = getCurrentInstance()
const store = useLanguageStore()
const auth = useAuthStore()
const register = useRegisterStore()
const emit = defineEmits(['toggle'])
const showPassword = ref(false)
const type = computed(() => showPassword.value ? "text" : "password")
const icon = computed(() => showPassword.value ? "fa-eye" : "fa-eye-slash")
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}
const registerForm = ref({
  phone: '',
  captcha: '',
  password: '',
  check: false
})
const errors = ref({
  phoneError: '',
  captchaError: '',
  passwordError: '',
  agreementError: ''
})
const gotoAgreement = (language) => {
  register.gotoAgreement()
  register.getData(registerForm.value.phone, registerForm.value.captcha, registerForm.value.password)
  router.push(`/agreement-${language}`)
}
onMounted(() => {
  registerForm.value.phone = register.registerData.phone
  registerForm.value.captcha = register.registerData.captcha
  if (register.backRegister) {
    registerForm.value.check = true
  }
})
const validatePhone = () => {
  const phone = registerForm.value.phone.trim()
  if (!/^1[3-9]\d{9}$/.test(phone)) {
    errors.value.phoneError = proxy.$t('error1')
    return false
  }
  errors.value.phoneError = ""
  return true
}
const countSecond = ref(0)
const isCount = ref(false)
const getCaptcha = async () => {
  if (!validatePhone()) return
  if (isCount.value) return
  isCount.value = true
  await fetchCaptcha(registerForm.value.phone) // 调用获取验证码API
  countSecond.value = 60
  ElMessage.success(proxy.$t('captchaTip2'))
  const timer = setInterval(() => {
    countSecond.value--
    if (countSecond.value <= 0) {
      clearInterval(timer)
      isCount.value = false
    }
  }, 1000)
}
const validateCaptcha = () => {
  const captcha = registerForm.value.captcha.trim()
  if (!/^\d{6}$/.test(captcha)) {
    errors.value.captchaError = proxy.$t('error3')
    return false
  }
  errors.value.captchaError = ''
  return true
}
const getTip = () => {
  if (!registerForm.value.check) {
    ElMessage.warning(proxy.$t('error4'))
  }
}
const validatePassword = () => {
  const password = registerForm.value.password;
  const regex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/
  if (!regex.test(password)) {
    errors.value.passwordError = proxy.$t('error2')
    return false
  }
  errors.value.passwordError = ""
  return true
}
const validateCheckBox = () => {
  if (!registerForm.value.check) {
    errors.value.agreementError = proxy.$t('error5')
    return false
  }
  errors.value.agreementError = ""
  return true
}
const resetErrors = () => {
  Object.keys(errors.value).forEach(key => {
    errors.value[key] = ''
  })
}

const tokenStore = useTokenStore();
const handleSubmit = async () => {
  resetErrors()
  const res1 = validatePhone()
  const res2 = validateCaptcha()
  const res3 = validateCheckBox()
  const res4 = validatePassword()
  if (!res1 || !res2 || !res3 || !res4) return
  await submitRegister(registerForm.value) // 调用提交注册表单API
  ElMessage.success('注册成功');
  // 自动登录
  const loginData = {
    phone: registerForm.value.phone,
    password: registerForm.value.password,
    remember: false
  }
  const result = await submitLogin(loginData)
  if(result && result.data){
    tokenStore.setToken(result.data)
    auth.setLogin(true)
    ElMessage.success('注册并登录成功');
    await router.push('/main')
  }else{
    ElMessage.error('自动登录失败，请手动登录')
  }
}
</script>

<template>
  <form novalidate action="" @submit.prevent="handleSubmit">
    <h2>{{ $t('register') }}</h2>
    <div class="input-group">
      <input type="text" id="phone" v-model="registerForm.phone" @blur="validatePhone" maxlength="11" required>
      <label for="registerPhone">{{ $t('phone') }}</label>
      <span class="error-msg" v-show="errors.phoneError">{{ errors.phoneError }}</span>
    </div>
    <div class="input-group">
      <input type="text" id="captcha" v-model="registerForm.captcha" @blur="validateCaptcha" maxlength="6" required>
      <label for="captcha">{{ $t('captcha') }}</label>
      <button type="button" class="get-code-btn" @click="getCaptcha" :disabled="isCount">
        <a v-if="!isCount">{{ $t('getCaptcha') }}</a>
        <a v-else>{{ countSecond }}{{ $t('captchaTip1') }}</a>
      </button>
      <span class="error-msg" v-show="errors.captchaError">{{ errors.captchaError }}</span>
    </div>
    <div class="input-group">
      <input :type=type @click.once="getTip" v-model="registerForm.password" @blur="validatePassword" name="password"
        maxlength="20" required>
      <label for="registerPassword">{{ $t('password') }}</label>
      <i class="fa-solid toggle-password" :class=icon @click="togglePasswordVisibility"></i>
      <span class="error-msg" v-show="errors.passwordError">{{ errors.passwordError }}</span>
    </div>
    <div class="remember">
      <label>
        <input type="checkbox" id="agreementCheck" v-model="registerForm.check" @change="validateCheckBox">
        {{ $t('agree') }}
        <a class="terms-link" @click.prevent="gotoAgreement(store.currentLang === 'zh' ? 'cn' : 'us')">
          {{ $t('agreement') }}
        </a>
      </label>
      <span class="error-msg" v-show="errors.agreementError">{{ errors.agreementError }}</span>
    </div>
    <button type="submit">{{ $t('register') }}</button>
    <div class="signin-link">
      <p>
        {{ $t('problem3') }}
        <a href="#" class="signin-btn-link" @click.prevent="emit('toggle')">{{ $t('toLogin') }}</a>
      </p>
    </div>
  </form>
</template>

<style scoped>
@import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css");
@import url("../../assets/styles/sign.css");

.get-code-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.get-code-btn a {
  text-decoration: none;
}
</style>